package com.everflourish.yeah100.act.markingsystem;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.adapter.TeacherSearchAdapter;
import com.everflourish.yeah100.entity.NewFriend;
import com.everflourish.yeah100.entity.marking.Teacher;
import com.everflourish.yeah100.entity.marking.TeacherModel;
import com.everflourish.yeah100.http.SettingRequest;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.collections.NewFriendCollections;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.everflourish.yeah100.utils.constant.RoleEnum;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lapism.searchview.SearchView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/4.
 * 时间：2016/7/4
 */
public class TeacherSearchActivity extends BaseActivity {

    private Toolbar mToolBar;
    private RecyclerView mTeacherList;
    private ArrayList<TeacherModel> mList;
    private ArrayList<TeacherModel> mCheckedTeacherModels;
    private TeacherSearchAdapter mAdapter;
    private SettingRequest mSettingRequest;
    private LoadDialog mLoadDialog;
    private String mCondition;
    private SearchView mSearchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teacher_share);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mSettingRequest = SettingRequest.getInstance();
        mList = new ArrayList<TeacherModel>();
        mCheckedTeacherModels = (ArrayList<TeacherModel>) getIntent()
                .getSerializableExtra(IntentUtil.CHECKED_TEACHERS);
        mCondition = getIntent().getStringExtra("condition");
        mAdapter = new TeacherSearchAdapter(mContext, mList, mQueue);
    }

    private void initView() {
        mToolBar = (Toolbar) findViewById(R.id.teacher_toolbar);
        mTeacherList = (RecyclerView) findViewById(R.id.teacher_share_list);
        mSearchView = (SearchView) findViewById(R.id.teacher_share_searchView);
        mSearchView.setVisibility(View.GONE);
    }

    private void configView() {
        mToolBar.setTitle("搜索老师");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishMenuActivity();
            }
        });
        mTeacherList.setLayoutManager(new LinearLayoutManager(mContext));
        mTeacherList.setAdapter(mAdapter);
        searchRegister(mCondition, 0, 0);
    }

    private void searchRegister(String condition, Integer startIndex,
                                Integer selectedCount) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在搜索老师中...", mQueue);
        JsonObjectRequest userLoginRequest = mSettingRequest.searchRequest(
                condition, startIndex, selectedCount,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        searchRegisterListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mSettingRequest.disposeError(mContext, mLoadDialog, error, "搜索老师失败");
                    }
                });
        mQueue.add(userLoginRequest);
//        mQueue.start();
    }

    private void searchRegisterListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.USER_INFOS);
                Gson gson = new Gson();
                Type type = new TypeToken<List<NewFriend>>() {
                }.getType();
                ArrayList<NewFriend> friendList = gson.fromJson(
                        jsonArray.toString(), type);
                if (friendList == null || friendList.size() == 0) {
                    MyToast.showShort(mContext, "没有找到");
                    return;
                }
                for (NewFriend f : friendList) {
                    if (f.getName().equals(Yeah100.loginInfo.userInfo.name)) {
                        friendList.remove(f);
                        break;
                    }
                }
                Collections.sort(friendList, new NewFriendCollections(false));
                setTeacherList(friendList);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.friend_040299_999999E);
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.friend_04021_000001E);
            } else {
                MyToast.showShort(mContext, "搜索老师失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "搜索老师失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 设置搜索老师的数据list
     *
     * @param list
     */
    private void setTeacherList(ArrayList<NewFriend> list) {
        if (list != null) {
            Collections.sort(list, new NewFriendCollections(true));
        }
        if (mCheckedTeacherModels == null) {
            mCheckedTeacherModels = new ArrayList<TeacherModel>();
        }
        for (NewFriend newFriend : list) {
            if (!RoleEnum.TEACHER.name.equals(newFriend.getRole())) {
                continue;
            }
            TeacherModel teacherModel = new TeacherModel();
            Teacher teacher = new Teacher();
            teacher.setUserId(newFriend.getId());
            teacher.setUserName(newFriend.getName());
            teacher.setNickName(newFriend.getNickName());
            teacherModel.setTeacher(teacher);
            mList.add(teacherModel);
        }
        for (TeacherModel teacherModel : mCheckedTeacherModels) {
            for (TeacherModel model : mList) {
                Teacher teacher = model.getTeacher();
                if (teacher.getUserId().equals(
                        teacherModel.getTeacher().getUserId())) {
                    model.setIsCheck(teacherModel.isCheck());
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 获取选中的newFriend集合
     *
     * @return
     */
    private ArrayList<TeacherModel> getCheckedNewFriends() {
        ArrayList<TeacherModel> checkedTeachers = new ArrayList<TeacherModel>();
        for (TeacherModel t : mList) {
            if (t.isCheck()) {
                checkedTeachers.add(t);
            }
        }
        return checkedTeachers;
    }

    private void finishMenuActivity() {
        Intent resultIntent = getIntent();
        resultIntent.putExtra(IntentUtil.FRIENDS, getCheckedNewFriends());
        this.setResult(RESULT_OK, resultIntent);
        IntentUtil.finishActivity(TeacherSearchActivity.this);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishMenuActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }
}
